package com.rg.inf.receiver;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rd.sys.common.base.CommonConstants;
import com.rd.sys.common.utils.CommonUtils;
import com.rd.sys.common.utils.GetWebConfig;
import com.rd.sys.common.utils.JacksonMapper;
import com.rd.sys.dto.commmon.base.EyeException;
import com.rd.sys.dto.commmon.base.EyeResult;
import com.rg.inf.action.DispatchAction;

public class SynFileServlet extends javax.servlet.http.HttpServlet {
    private static final long serialVersionUID = 6647651195373870689L;
    private static final int Sync_File_Max_Size = GetWebConfig.getInt("inf.sync.file.max.size", 100);
    private static final int Sync_File_Threshold_Size = GetWebConfig.getInt("inf.sync.file.threshold.size", 1000);
    private static final String Sync_File_Temp_Path = CommonUtils.judgeConfigPath(GetWebConfig
            .getValue("inf.sync.file.temp.path"));
    protected static final Logger logger = LoggerFactory.getLogger(SynFileServlet.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {

        try {
            /** 1. 定义待处理的变量 */
            String userCode = null;
            String message = null;
            List<FileItem> fileItems = new ArrayList<FileItem>();

            /** 2. 分解处理HTTP MIME消息 */
            // 为该请求创建一个DiskFileItemFactory对象，通过它来解析请求。
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 设置允许用户上传文件大小,单位:字节
            upload.setSizeMax(Sync_File_Max_Size * 1024 * 1024);
            // 设置最多只允许在内存中存储的数据,单位:字节
            factory.setSizeThreshold(Sync_File_Threshold_Size * 1024);
            // 设置一旦文件大小超过阈值时数据存放在硬盘的目录
            factory.setRepository(new File(Sync_File_Temp_Path));

            List<FileItem> items = upload.parseRequest(request); // 执行解析后，所有的表单项目都保存在一个List中
            Iterator<FileItem> it = items.iterator();
            while (it.hasNext()) {
                FileItem item = (FileItem) it.next();
                if (item.isFormField()) {
                    // 如果是普通表单
                    String fieldName = item.getFieldName();
                    if (fieldName.equals("EYEUSER")) {
                        userCode = item.getString();
                    } else if (fieldName.equals("EYEOBJECT")) {
                        message = item.getString();
                    }

                } else {
                    // 如果是上传文件, 则保存待进一步处理
                    fileItems.add(item);

                }
            }

            /** 3. 判断处理消息的合法性,正确则交由分发器处理 */
            if (userCode == null || message == null || fileItems.size() <= 0) {
                throw new Exception("the request message is not correct");
            }

            /** 4. 交由统一分发Action处理 */
            String respMessage = new DispatchAction().execute(userCode, message, fileItems);

            /** 5. 响应给客户端 */
            response2Client(response, respMessage);

        } catch (EyeException ex) {
            response2ClientError(response, new EyeResult(ex.getResult()));
        } catch (Exception ex) {
            logger.error("", ex);
            response2ClientError(response, new EyeResult(EyeResult.ResultDefine.COMMON_OTHER_ERROR_CLIENT));
        }
    }

    /**
     * 响应给客户端
     * 
     * @param response
     * @param interBossResp
     * @throws IOException
     */
    private void response2Client(HttpServletResponse response, String respMessage) throws IOException {
        logger.info("the response message is: " + respMessage);
        response.setCharacterEncoding(CommonConstants.SysParamConstants.SYS_CHARSET);
        response.setHeader("Content-Type", "application/x-www-form-urlencoded");

        PrintWriter writer = response.getWriter();
        writer.print(respMessage);
        writer.flush();
        writer.close();
    }

    /**
     * 响应给客户端(400错误码)
     * 
     * @param response
     * @param result
     * @throws IOException
     */
    private void response2ClientError(HttpServletResponse response, EyeResult result) throws IOException {
        String respMessage = JacksonMapper.bean2Json(result);
        logger.info("the response message is: " + respMessage);
        response.setCharacterEncoding(CommonConstants.SysParamConstants.SYS_CHARSET);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, respMessage);
    }
}
